package com.aike.user_center_practice.controller;


import com.aike.user_center_practice.common.BaseResponse.BaseResponse;
import com.aike.user_center_practice.common.BaseResponse.ErrorCode;
import com.aike.user_center_practice.common.BaseResponse.ResultUtils;
import com.aike.user_center_practice.exception.BusinessException;
import com.aike.user_center_practice.model.request.UserLoginRequest;
import com.aike.user_center_practice.model.request.UserRegisterRequest;
import com.aike.user_center_practice.model.domain.User;
import com.aike.user_center_practice.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.aike.user_center_practice.contant.UserConstant.*;

/**
 * 用户接口
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;

    /**
     * 用户注册
     * controller层倾向于对请求参数本身的校验，不涉及业务逻辑本身；
     * service层是对业务逻辑的校验。
     * @param userRegisterRequest 请求体
     * @return 用户id
     */
    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {

        if (userRegisterRequest == null) {
            // 直接返回异常 return ResultUtils.error(ErrorCode.PARAMS_ERROR);
            throw new BusinessException(ErrorCode.PARAMS_ERROR); // 直接抛出异常
        }
        String userAccount = userRegisterRequest.getUserAccount();

        String userPassword = userRegisterRequest.getUserPassword();

        String checkPassword = userRegisterRequest.getCheckPassword();

        String planeCode = userRegisterRequest.getPlaneCode();

        // 先检验上述参数：若任意一个为空，则返回null
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword, planeCode)) {
            throw new BusinessException(ErrorCode.NULL_ERROR); // 直接抛出异常
        }
        long userId = userService.userRegister(userAccount, userPassword, checkPassword, planeCode);
        return ResultUtils.success(userId);
    }

    /**
     * 用户进行登录：
     * controller层倾向于对请求参数本身的校验，不涉及业务逻辑本身；
     * service层是对业务逻辑的校验。
     * 故，controller层做校验：有可能被controller之外的类调用
     * @param userLoginRequest session
     * @return 用户
     */
    @PostMapping("/login")
    public BaseResponse<User> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {

        if (userLoginRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "userLoginRequest 在u为空。"); // 直接抛出异常
        }
        String userAccount = userLoginRequest.getUserAccount();

        String userPassword = userLoginRequest.getUserPassword();
        // 先检验上述参数：若任意一个为空，则返回null<--这里做校验，上述有更好的解释
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "登录的Account/Password为空。");
        }
        User user = userService.userLogin (userAccount, userPassword, request);
        return ResultUtils.success(user);
    }

    /**
     * 获取用户的登录状态：获取用户的当前登录信息接口
     * @param request 请求
     * @return 返回脱敏后的用户信息
     */
    @GetMapping("/current")
    public BaseResponse<User> getUserCurrent(HttpServletRequest request) {
        Object userObject = request.getSession().getAttribute(USER_LOGIN_STATUS); // 获取用户的登录信息
        User currentUser = (User) userObject;
        if (currentUser == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "没有用户存在。");
        }
        long userId = currentUser.getId();
        // 校验用户是否合法
        User user = userService.getById(userId);
        User safeUser = userService.getSafetyUser(user);
        return ResultUtils.success(safeUser);
    }
    /**
     * 用户昵称查询
     * @param username 查询用户
     * @return 返回列表
     */
    @GetMapping("/search")
    public BaseResponse<List<User>> searchUsers(String username, HttpServletRequest request) {
        // 一定要进行用户鉴权！！！！
        if(!isAdmin(request)){
            List<User> emptyUsers = new ArrayList<>();
            return ResultUtils.success(emptyUsers);
        }
        // 查询用户昵称
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(username)) {
            queryWrapper.like("username", username); // 模糊查询
        }
        List<User> userslist = userService.list(queryWrapper);
        // 做了一个过滤器，将密码设置为空，然后再返回
        List<User> userd = userslist.stream().map(user -> userService.getSafetyUser(user)).collect(Collectors.toList());
        return ResultUtils.success(userd);
    }

    /**
     * 删除用户id
     * @param userId 用户id
     * @return 返回布尔类型
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteUsers(@RequestBody long userId, HttpServletRequest request) {
        if(!isAdmin(request)){
            throw new BusinessException(ErrorCode.NULL_AUTH, "用户无权限。");
        }
        // 逻辑删除
        if (userId <= NORMAL_NUMBER_ZERO) {
            throw new BusinessException(ErrorCode.NULL_ERROR, "逻辑删除，没有数据。");
        }
        boolean boolUser = userService.removeById(userId);
        return ResultUtils.success(boolUser);
    }

    /**
     * 退出登录态：清除登录态
     * @param request session请求
     * @return 成功，则返回1；反之，则返回null
     */
    @PostMapping("/layout")
    public BaseResponse<Integer> UserLayout(HttpServletRequest request) {
        if(request == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数错误。");
        }
        Integer ExitID = userService.userLogout(request);
        return ResultUtils.success(ExitID);
    }
    /**
     * 是否为管理员的方法
     * @param request 请求
     * @return 布尔
     */
    private boolean isAdmin(HttpServletRequest request) {
        // 仅管理员可以查询
        Object user = request.getSession().getAttribute(USER_LOGIN_STATUS);
        User userManger = (User) user;
        return userManger != null && userManger.getUserRole() == DEFAULT_MANAGER_STATUS;
    }
}
